//
//  TMGMarketHeaderView.m
//  TMGold
//
//  Created by Mac on 2017/12/15.
//  Copyright © 2017年 tangmu. All rights reserved.
//

#import "TMGMarketHeaderView.h"
#import "STMenuControl.h"
#import "TMWaveView.h"
#import "TMGGuessModel.h"
#import "TMGYLineModel.h"
#import "TMGXLineModel.h"
@interface TMGMarketHeaderView()<ChartViewDelegate,IChartAxisValueFormatter>

@property(nonatomic, strong) STButton                           *priceFromButton;
@property(nonatomic, strong) STSegementButton                   *segementButton;
@property(nonatomic, strong) LineChartView                      *chartView;
@property(nonatomic, strong) NSArray                            *options;
@property(nonatomic, strong) STLabel                     *peopleLable;
@property(nonatomic, strong) ChartYAxis                     *leftAxis;//y轴
@property(nonatomic, strong) STLabel                     *desLable;
@end
@implementation TMGMarketHeaderView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self configSubView];
    }
    return self;
}
- (void)setGoldHistoryArray:(NSArray<TMGGoldHistoryModel *> *)goldHistoryArray{
    _goldHistoryArray = goldHistoryArray;
    [self configChartView];
    [self chartViewData];
}
#pragma mark --subView
- (void)configSubView{
    self.backgroundColor = [UIColor whiteColor];
    UIImageView * bannerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 193)];
    bannerImageView.image = [UIImage imageNamed:@"wdebanner"];
    bannerImageView.userInteractionEnabled = YES;
    [self addSubview:bannerImageView];
    
    
    self.todayLable = [[STLabel alloc] initWithFrame:CGRectMake(15, 25, UIScreenWidth - 30, 40)
                                                text:@"236.14↑0.88%"
                                           textColor:[UIColor whiteColor]
                                                font:28
                                         isSizetoFit:NO
                                       textAlignment:NSTextAlignmentCenter];
    self.todayLable.attributedText = [self.todayLable.text st_convertAttributeStringWithKeyWord:@"↑0.88%" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    [self addSubview:self.todayLable];
    
    __weak typeof(self) weakSelf =  self;
    self.priceFromButton = [[STButton alloc] initWithFrame:CGRectMake(0, self.todayLable.bottom + 10, UIScreenWidth, 44)
                                                     title:@"金价来源"
                                                titleColor:[UIColor whiteColor]
                                                 titleFont:12
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:nil];
    [weakSelf.priceFromButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedPriceFromButton:sender];
    }];
    self.priceFromButton.centerX = UIScreenWidth / 2;
    [self.priceFromButton makeImageRight];
    self.priceFromButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self addSubview:self.priceFromButton];
    
    self.segementButton = [[STSegementButton alloc] initWithFrame:CGRectMake(0, bannerImageView.bottom, UIScreenWidth - 100, 44)
                                                         andTitle:@[@"24小时",@"7天",@"30天",@"65天"] handle:^(STSegementButton *sender) {
                                                             [weakSelf onSelectedSegementButtonWithIndex:sender.tag];
                                                         }];
    self.segementButton.backgroundColor = [UIColor whiteColor];
    self.segementButton.lineSelectedColor = TM_orangeColor;
    self.segementButton.butTitleSelectedColor = TM_orangeColor;
    self.segementButton.butTitleColor = TM_secendTextColor;
    self.segementButton.lineColor = [UIColor whiteColor];
    self.segementButton.cureentIndex = 0;
    self.segementButton.autoMoveWithClic = YES;
   // [self addSubview:self.segementButton];
    
    STButton * historyButton = [[STButton alloc] initWithFrame:CGRectMake(self.segementButton.right, bannerImageView.bottom, 100, 44)
                                                         title:@"历史走势"
                                                    titleColor:TM_firstTextColor
                                                     titleFont:14
                                                  cornerRadius:0
                                               backgroundColor:nil
                                               backgroundImage:nil
                                                         image:[UIImage imageNamed:@"三角形拷贝"]];
    historyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [historyButton makeImageRight];
    [historyButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedHistoryButton:sender];
    }];
  //  [self addSubview:historyButton];
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(20, bannerImageView.bottom, UIScreenWidth - 40, 44)
                                                     text:@""
                                                textColor:SecendTextColor
                                                     font:13
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    self.desLable = titleLable;
    [self addSubview:self.desLable];
    [self configChartView];

    
    STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(0, self.chartView.bottom, UIScreenWidth / 2, 50)
                                                     title:@"买入"
                                                titleColor:[UIColor whiteColor]
                                                 titleFont:18
                                              cornerRadius:0
                                           backgroundColor:TM_orangeColor
                                           backgroundImage:nil
                                                     image:nil];
    buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [buyButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedBuyButton:sender];
    }];
    [buyButton st_showBottomLine];
    [buyButton st_showTopLine];
    [self addSubview:buyButton];
    
    STButton * saleButton = [[STButton alloc] initWithFrame:CGRectMake(buyButton.right, self.chartView.bottom, UIScreenWidth / 2, 50)
                                                      title:@"卖出"
                                                 titleColor:TM_orangeColor
                                                  titleFont:18
                                               cornerRadius:0
                                            backgroundColor:[UIColor whiteColor]
                                            backgroundImage:nil
                                                      image:nil];
    [saleButton st_showBottomLine];
    [saleButton st_showTopLine];
    saleButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [saleButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedSalemButton:sender];
    }];
    [self addSubview:saleButton];
    
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, buyButton.bottom, UIScreenWidth-0, 169)];
    imageView.image = [UIImage imageNamed:@"组8"];
    imageView.userInteractionEnabled = YES;
    [self addSubview:imageView];
    
    UIView * grawView = [[UIView alloc] initWithFrame:CGRectMake(0, imageView.bottom, UIScreenWidth, 10)];
    grawView.backgroundColor = TM_backgroundColor;
    [self addSubview:grawView];
    
    UIView * sectionView = [[TMGSectionHeaderView alloc] initWithFrame:CGRectMake(0, grawView.bottom, UIScreenWidth, 44) color:TM_orangeColor title:@"金价预测"];
    sectionView.backgroundColor = [UIColor whiteColor];
    [self addSubview:sectionView];
    
    
    self.peopleLable = [[STLabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)
                                                 text:@"167人正在参与"
                                            textColor:TM_orangeColor
                                                 font:14
                                          isSizetoFit:NO
                                        textAlignment:NSTextAlignmentRight];
    self.peopleLable.attributedText = [self.peopleLable.text st_convertAttributeStringWithKeyWord:@"人正在参与" attributes:@{NSForegroundColorAttributeName:TM_secendTextColor}];
    self.peopleLable.right = UIScreenWidth - 15;
    [sectionView st_showBottomLine];
    [sectionView addSubview:self.peopleLable];
    

    self.upWaveControl = [[TMWaveView alloc] initWithFrame:CGRectMake(0, sectionView.bottom, UIScreenWidth / 2, 100)
                                              waveTopColor:TM_redColor
                                           waveBootomColor:FlatWhiteDark
                                                     title:@"80%de人看涨"
                                                titleColor:TM_redColor
                                                   persent:0.8];
    
    
    [self.upWaveControl addTarget:self action:@selector(onSelectedControl:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.upWaveControl];
    
   
    
    self.lowWaveControl = [[TMWaveView alloc] initWithFrame:CGRectMake(_upWaveControl.right, sectionView.bottom, UIScreenWidth / 2, 100)
                                               waveTopColor:FlatMint
                                            waveBootomColor:FlatWhiteDark
                                                      title:@"20%de人看跌"
                                                 titleColor:FlatMint
                                                    persent:0.1];
    
    
    [self.lowWaveControl addTarget:self action:@selector(onSelectedControl:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.lowWaveControl];
    

   
    
    UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, _lowWaveControl.bottom, UIScreenWidth, 0.5)];
    line.backgroundColor = TM_lineColor;
    [self addSubview:line];
    
    STButton * lowButton = [[STButton alloc] initWithFrame:CGRectMake(0, line.bottom, UIScreenWidth / 3, 44)
                                                     title:@"看跌"
                                                titleColor:TM_thirdTextColor
                                                 titleFont:13
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:[UIImage imageNamed:@"看跌_01"]];
    lowButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [lowButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedLowButton:sender];
    }];
    [lowButton st_showRightLine:30];
    lowButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [self addSubview:lowButton];
    
     CGRect temRect = lowButton.frame;
    
    STButton * upButton = [[STButton alloc] initWithFrame:CGRectMake(lowButton.right, line.bottom, UIScreenWidth / 3, 44)
                                                    title:@"看涨"
                                               titleColor:TM_redColor
                                                titleFont:13
                                             cornerRadius:0
                                          backgroundColor:nil
                                          backgroundImage:nil
                                                    image:[UIImage imageNamed:@"看涨_01"]];
    upButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [upButton st_showRightLine:30];
    upButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [upButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedUpButton:sender];
    }];
    [self addSubview:upButton];
    
    STButton * commentButton = [[STButton alloc] initWithFrame:CGRectMake(upButton.right, line.bottom, UIScreenWidth / 3, 44)
                                                         title:@"评论"
                                                    titleColor:TM_secendTextColor
                                                     titleFont:13
                                                  cornerRadius:0
                                               backgroundColor:nil
                                               backgroundImage:nil
                                                         image:[UIImage imageNamed:@"评论"]];
    commentButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    commentButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [commentButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedCommentButton:sender];
    }];
    [self addSubview:commentButton];
    
    lowButton.frame = upButton.frame;
    upButton.frame = temRect;
    
    
    self.height = commentButton.bottom;
    self.height = grawView.bottom;//5/9 隐藏金价预测，
    self.clipsToBounds = YES;
    UIView * headers = [[UIView alloc] initWithFrame:CGRectMake(0, -bannerImageView.height, UIScreenWidth, 2 * bannerImageView.height)];
    headers.backgroundColor = TM_orangeColor;
    [self insertSubview:headers atIndex:0];
    
}
- (void)configChartView{

    [self.chartView removeFromSuperview];
    self.chartView = [[LineChartView alloc] initWithFrame:CGRectMake(10, 100, UIScreenWidth - 20, 300)];
    _chartView.delegate = self;
    _chartView.chartDescription.enabled = NO;
    _chartView.dragEnabled = YES;
    [_chartView setScaleEnabled:NO];
    _chartView.pinchZoomEnabled = NO;
    _chartView.drawGridBackgroundEnabled = NO;
    _chartView.chartDescription.enabled = NO; //不显示描述label
     _chartView.legend.form = ChartLegendFormNone;   //说明图标
    
    // x-axis limit line
//    ChartLimitLine *llXAxis = [[ChartLimitLine alloc] initWithLimit:10.0 label:@"Index 10"];
//    llXAxis.lineWidth = 4;
//    llXAxis.lineDashLengths = @[@(10.f), @(10.f), @(0.f)];
//    llXAxis.labelPosition = ChartLimitLabelPositionRightBottom;
//    llXAxis.valueFont = [UIFont systemFontOfSize:10.f];
//
//    _chartView.xAxis.enabled = NO;
//
//    ChartLimitLine *ll1 = [[ChartLimitLine alloc] initWithLimit:150.0 label:@"Upper Limit"];
//    ll1.lineWidth = 4.0;
//    ll1.lineDashLengths = @[@5.f, @5.f];
//    ll1.labelPosition = ChartLimitLabelPositionRightTop;
//    ll1.valueFont = [UIFont systemFontOfSize:10.0];
//
//    ChartLimitLine *ll2 = [[ChartLimitLine alloc] initWithLimit:-30.0 label:@"Lower Limit"];
//    ll2.lineWidth = 4.0;
//    ll2.lineDashLengths = @[@5.f, @5.f];
//    ll2.labelPosition = ChartLimitLabelPositionRightBottom;
//    ll2.valueFont = [UIFont systemFontOfSize:10.0];
    
    NSArray <TMGGoldHistoryModel*>* nixuArray =
    [self.goldHistoryArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        TMGGoldHistoryModel *tNumber1 = (TMGGoldHistoryModel *)obj1;
        TMGGoldHistoryModel *tNumber2 = (TMGGoldHistoryModel *)obj2;
        //因为不满足sortedArrayUsingComparator方法的默认排序顺序，则需要交换
        if ([tNumber1.price floatValue] < [tNumber2.price floatValue])
            return NSOrderedDescending;
        return NSOrderedAscending;

    }];
    
    self.chartView.rightAxis.enabled = NO;
    //不绘制右边轴
    ChartYAxis *leftAxis = self.chartView.leftAxis;
    //获取左边Y轴
    leftAxis.labelCount = 5;//Y轴label数量，数值不一定，如果forceLabelsEnabled等于YES, 则强制绘制制定数量的label, 但是可能不平均
    leftAxis.forceLabelsEnabled = YES;
    //不强制绘制指定数量的label //
//    leftAxis.axisMinValue = nixuArray.firstObject.price.floatValue;
//    //设置Y轴的最小值
//    //
//    leftAxis.axisMaxValue = nixuArray.lastObject.price.floatValue;
    //设置Y轴的最大值
    leftAxis.inverted = NO;
    //是否将Y轴进行上下翻转
    leftAxis.axisLineColor = [UIColor clearColor];
    //Y轴颜色
    leftAxis.labelPosition = YAxisLabelPositionOutsideChart;
    //label位置
    leftAxis.labelTextColor = SecendTextColor;
    //文字颜色
    leftAxis.labelFont = [UIFont systemFontOfSize:10.0f];
    //文字字体
    leftAxis.gridColor = SecendTextColor;
    //网格线颜色
    leftAxis.gridAntialiasEnabled = NO;//开启抗锯齿
    
    

    
    ChartXAxis *xAxis = self.chartView.xAxis;
    xAxis.granularityEnabled = YES;
    //设置重复的值不显示
    xAxis.labelPosition= XAxisLabelPositionBottom;
    xAxis.labelCount  = 5;
//    xAxis.forceLabelsEnabled = YES;
//    xAxis.granularity = 0;
    xAxis.axisMinimum = - 1;
    xAxis.axisMaximum = 181;
//    xAxis.xOffset = 1;

    //设置x轴数据在底部 xAxis.gridColor = [UIColor clearColor];
    xAxis.labelTextColor = SecendTextColor;
    //文字颜色
    xAxis.axisLineColor = [UIColor grayColor];
    xAxis.gridColor = [UIColor clearColor];
    xAxis.valueFormatter = [[TMGXLineModel alloc] initWithDataSouce:self.goldHistoryArray];
  //  self.chartView.maxVisibleCount = self.goldHistoryArray.count;//设置能够显示的数据数量



    self.chartView.frame = CGRectMake(20, self.desLable.bottom, UIScreenWidth - 40, 200);
    [self addSubview:self.chartView];
    
}
#pragma mark --Private Method
- (void)chartViewData{
    NSArray <TMGGoldHistoryModel*>* nixuArray =
    [self.goldHistoryArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        TMGGoldHistoryModel *tNumber1 = (TMGGoldHistoryModel *)obj1;
        TMGGoldHistoryModel *tNumber2 = (TMGGoldHistoryModel *)obj2;
        //因为不满足sortedArrayUsingComparator方法的默认排序顺序，则需要交换
        if ([tNumber1.price floatValue] < [tNumber2.price floatValue])
            return NSOrderedDescending;
        return NSOrderedAscending;
        
    }];
    
    //不强制绘制指定数量的label //
//   self.chartView.leftAxis.axisMinValue = nixuArray.lastObject.price.floatValue;
//    //设置Y轴的最小值
//    //
//    self.chartView.leftAxis.axisMaxValue = nixuArray.firstObject.price.floatValue;
    
    self.chartView.xAxis.valueFormatter = [[TMGXLineModel alloc] initWithDataSouce:self.goldHistoryArray];
    NSArray * array = self.goldHistoryArray;
    NSMutableArray *nowArray = [NSMutableArray new];
    
    for (TMGGoldHistoryModel * model in array) {
        CGFloat x = model.create_atIndex ;
        CGFloat y = [model.price floatValue];
        ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:x y:y];
        [nowArray addObject:entry];
    }
    LineChartDataSet *set1 = [[LineChartDataSet alloc] initWithValues:nowArray label:@""];
    set1.drawIconsEnabled = NO;
    [set1 setColor:TM_orangeColor];
    [set1 setCircleColor:UIColor.blackColor];
    set1.lineWidth = 1.0;
    set1.drawCircleHoleEnabled = NO;
    set1.drawValuesEnabled = NO;
    set1.circleRadius = 0;
    set1.valueFont = [UIFont systemFontOfSize:9.f];
    set1.highlightEnabled = YES;//选中拐点,是否开启高亮效果(显示十字线)
    set1.highlightColor = TM_orangeColor;// 十字线颜色
    set1.formLineWidth = 1.0;
    set1.formSize = 15.0;
    NSArray *gradientColors = @[
                                (id)FlatWhiteDark.CGColor,
                                (id)FlatWhite.CGColor
                                ];
    UIColor  *color = [UIColor clearColor];
    gradientColors = @[(id)color.CGColor,(id)color.CGColor];
    CGGradientRef gradient = CGGradientCreateWithColors(nil, (CFArrayRef)gradientColors, nil);
    
    set1.fillAlpha = 0.5;
    set1.fill = [ChartFill fillWithLinearGradient:gradient angle:90.f];
    set1.drawFilledEnabled = YES;
    set1.label = @"";
    
    CGGradientRelease(gradient);
    LineChartData *data = [[LineChartData alloc] initWithDataSets:@[set1]];
    self.chartView.data = data;

}

#pragma mark --Action Method
- (void)onSelectedPriceFromButton:(UIButton*)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(headerView:onSelectedPriceFromButton:)]) {
        [self.delegate headerView:self onSelectedPriceFromButton:sender];
    }
}
- (void)onSelectedSegementButtonWithIndex:(NSInteger)index{
    if (self.delegate && [self.delegate respondsToSelector:@selector(headerView:onSelectedSegementButtonWithIndex:)]) {
        [self.delegate headerView:self onSelectedSegementButtonWithIndex:index];
    }
    
}
- (void)onSelectedHistoryButton:(UIButton*)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(headerView:onSelectedHistoryButton:)]) {
        [self.delegate headerView:self onSelectedHistoryButton:sender];
    }
}
- (void)onSelectedBuyButton:(UIButton*)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(headerView:onSelectedBuyButton:)]) {
        [self.delegate headerView:self onSelectedBuyButton:sender];
    }
}
- (void)onSelectedSalemButton:(UIButton*)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(headerView:onSelectedSalemButton:)]) {
        [self.delegate headerView:self onSelectedSalemButton:sender];
    }
}
- (void)onSelectedLowButton:(UIButton*)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(headerView:onSelectedLowButton:)]) {
        [self.delegate headerView:self onSelectedLowButton:sender];
    }
}
- (void)onSelectedUpButton:(UIButton*)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(headerView:onSelectedUpButton:)]) {
        [self.delegate headerView:self onSelectedUpButton:sender];
    }
}
- (void)onSelectedCommentButton:(UIButton*)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(headerView:onSelectedCommentButton:)]) {
        [self.delegate headerView:self onSelectedCommentButton:sender];
    }
}
- (void)onSelectedControl:(TMWaveView*)control{
    if (self.delegate && [self.delegate respondsToSelector:@selector(headerView:onSelectedControl:)]) {
        [self.delegate headerView:self onSelectedControl:control];
    }
}
- (void)setGuessModel:(TMGGuessModel *)guessModel{
    _guessModel = guessModel;
    CGFloat up = [[[guessModel.up componentsSeparatedByString:@"%"] firstObject] floatValue]/100;
    CGFloat down = [[[guessModel.down componentsSeparatedByString:@"%"] firstObject] floatValue]/100;
    self.upWaveControl.wavePresent = up;
    self.lowWaveControl.wavePresent = down;
    
    self.upWaveControl.titleLable.text = [NSString stringWithFormat:@"%@的人看涨",guessModel.up];
    self.lowWaveControl.titleLable.text = [NSString stringWithFormat:@"%@的人看跌",guessModel.down];
    self.peopleLable.text = [NSString stringWithFormat:@"%@人正在参与",guessModel.total];
    self.peopleLable.attributedText = [self.peopleLable.text st_convertAttributeStringWithKeyWord:@"人正在参与" attributes:@{NSForegroundColorAttributeName:TM_secendTextColor}];
}
#pragma mark --chart 代理
- (void)chartValueSelected:(ChartViewBase * _Nonnull)chartView entry:(ChartDataEntry * _Nonnull)entry highlight:(ChartHighlight * _Nonnull)highlight {
    
    NSInteger index = entry.x  ;
    TMGGoldHistoryModel * model =  self.goldHistoryArray[index - 1];
    self.desLable.text = [NSString stringWithFormat:@"%@ | %@元(克)",model.create_at,model.price];
  //  _markY.text = [NSString stringWithFormat:@"%ld%%",(NSInteger)entry.y];
    //将点击的数据滑动到中间
//    [self.chartView centerViewToAnimatedWithXValue:entry.x yValue:entry.y axis:[self.chartView.data getDataSetByIndex:highlight.dataSetIndex].axisDependency duration:1.0];
    
    
}
@end

